package com.example.mei.blueautosend.chart;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.PathEffect;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


import com.example.mei.blueautosend.R;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 折线View
 *
 * @author licq
 */
public class JiSuLineView extends View {
    OnTmpViewMoveListener listener = null;
    List<XAxisScale> crossAxis = new ArrayList<XAxisScale>();// 横轴刻度
    List<JiSuLinePoint> foldLinePoints = new ArrayList<JiSuLinePoint>();// 折线点
    private int foldLineColor;// 折线的颜色
    private int verticalAxisColor;// 纵轴的颜色
    SimpleDateFormat format = new SimpleDateFormat("dd");
    private int crossAxisColor;// 横轴的颜色
    private int crossAxisScaleTextColor;// 横轴刻度文字的颜色
    private int crossAxisScaleTextSize;// 横轴刻度文字的大小
    private int axisWidth;// 纵、横轴宽度
    private int axisScaleWidth = 50;// 纵、横刻度宽度
    private boolean isFillMode;// 是否是填充模式
    private boolean isDrawFoldLineCircle;// 是否绘制折线点的圆圈
    private int foldLineCircleRadius;// 折线点圆圈的半径
    private int foldLineCircleColor;// 折线点圆圈的颜色
    private int foldLineWidth = 5;// 折线的宽度
    private int foldLineOuterColor;
    private int currentPPP = 0;
    private int foldLineCount = 10;// 每屏显示的折线数量
    private int startIndex;// 绘制折线点的起始位置
    private int endIndex;// 绘制折线点的结束位置
    private int foldLineDis;// 绘制的间隔距离
    private int count = 1;
    private Paint verticalAxisPaint;
    private Paint crossAxisPaint;
    private Paint crossAxispScalePaint;
    private Paint verticalAxisTextPaint;
    private Paint crcossAxisTextPaint;
    private Paint foldLineTmpPaint;
    private Paint foldLineOutPaint;
    private Paint foldLineCirclePaint;
    private Paint foldLineCircleTmpPaint;

    private Paint tipTextNODPaint;
    private Paint verticalAxisLargePaint;
    private Paint yearPaint;
    DecimalFormat df = new DecimalFormat("0");
    private int foldLineAreaWidth;// 折线图的宽度
    private int moveX = -100;//之前-100

    private int lastTouchX;

    private int dayBetween;
    private int firstMoveX = 0;

    private int min;
    private int max;

    public JiSuLineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray typeArray = getContext().obtainStyledAttributes(attrs, R.styleable.foldline);
        foldLineColor = typeArray.getColor(R.styleable.foldline_foldLineColor, getResources().getColor(R.color.black));
        verticalAxisColor = typeArray.getColor(R.styleable.foldline_verticalAxisColor, getResources().getColor(R.color.black));
        crossAxisColor = typeArray.getColor(R.styleable.foldline_crossAxisColor, getResources().getColor(R.color.black));
        axisWidth = typeArray.getDimensionPixelSize(R.styleable.foldline_axisWidth, 15);
        axisScaleWidth = typeArray.getDimensionPixelSize(R.styleable.foldline_axisScaleWidth, 10);
        isFillMode = typeArray.getBoolean(R.styleable.foldline_isFillMode, true);
        isDrawFoldLineCircle = typeArray.getBoolean(R.styleable.foldline_isDrawFoldLineCircle, true);
        foldLineCircleRadius = typeArray.getDimensionPixelSize(R.styleable.foldline_foldLineCircleRadius, 10);
        foldLineCircleColor = typeArray.getColor(R.styleable.foldline_foldLineCircleColor, Color.WHITE);
        crossAxisScaleTextColor = typeArray.getColor(R.styleable.foldline_crossAxisScaleTextColor, Color.BLACK);
        crossAxisScaleTextSize = typeArray.getColor(R.styleable.foldline_crossAxisScaleTextSize, 20);
        foldLineOuterColor = typeArray.getColor(R.styleable.foldline_foldLineOuterColor, Color.WHITE);


        typeArray.recycle();
        initPaint();
    }

    public void initPaint() {
        verticalAxisPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        crossAxisPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        verticalAxisTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        crcossAxisTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        crossAxispScalePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        foldLineTmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        foldLineOutPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        foldLineCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        foldLineCircleTmpPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        tipTextNODPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        verticalAxisLargePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        yearPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        verticalAxisPaint.setColor(crossAxisColor);
        verticalAxisPaint.setStyle(Style.STROKE);
        verticalAxisPaint.setStrokeWidth(axisWidth);


        // 横轴参数初始化
        crossAxisPaint.setColor(crossAxisColor);
        crossAxisPaint.setStyle(Style.STROKE);
        crossAxisPaint.setStrokeWidth(axisWidth);

        // 横轴刻度参数初始化
        crossAxispScalePaint.setColor(getResources().getColor(R.color.e_gray));
        crossAxispScalePaint.setStyle(Style.STROKE);
        crossAxispScalePaint.setStrokeWidth(DpXpExchange.dip2px(getContext(), (float) 0.5));
        // 横轴刻度文字
        crcossAxisTextPaint.setColor(getResources().getColor(R.color.gray));
        crcossAxisTextPaint.setTextSize(DpXpExchange.sp2px(getContext(), 10));
        // 纵轴刻度文字
        verticalAxisTextPaint.setColor(getResources().getColor(R.color.chart_text_gray));
        verticalAxisTextPaint.setTextSize(DpXpExchange.sp2px(getContext(), 10));
        verticalAxisLargePaint.setColor(getResources().getColor(R.color.chart_text_gray));
        ;
        verticalAxisLargePaint.setTextSize(DpXpExchange.sp2px(getContext(), 14));
        // 折线初始化
        foldLineTmpPaint.setColor(foldLineCircleColor);
        foldLineTmpPaint.setStrokeWidth(DpXpExchange.sp2px(getContext(), 1));
        foldLineTmpPaint.setStyle(Style.STROKE);
        // 折线轮廓
        foldLineOutPaint.setColor(foldLineColor);
        foldLineOutPaint.setStrokeWidth(DpXpExchange.sp2px(getContext(), 1));
        foldLineOutPaint.setStyle(Style.STROKE);


        //温度提示的paint
        tipTextNODPaint.setColor(getResources().getColor(R.color.gray));
        tipTextNODPaint.setTextSize(DpXpExchange.sp2px(getContext(), 24));

        yearPaint.setColor(getResources().getColor(R.color.gray));
        yearPaint.setTextSize(DpXpExchange.sp2px(getContext(), 10));



        // 折线外圆圈
        foldLineCirclePaint.setColor(foldLineOuterColor);
        foldLineCirclePaint.setStrokeWidth(DpXpExchange.dip2px(getContext(), (float) 1));
        foldLineCirclePaint.setStyle(Style.STROKE);
        foldLineCirclePaint.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
        // 折线内圆圈

        foldLineCircleTmpPaint.setColor(foldLineCircleColor);
        foldLineCircleTmpPaint.setStrokeWidth(DpXpExchange.dip2px(getContext(), (float) 1));
        foldLineCircleTmpPaint.setStyle(Style.STROKE);
        foldLineCircleTmpPaint.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));

    }

    public void initData(List<XAxisScale> crossAxisScales,
                         List<JiSuLinePoint> foldLineMaxPoints, int viewCount, int dayBetween
                         ,int min,int max
    ) {
        this.min = min;
        this.max = max;
        this.crossAxis = crossAxisScales;
        this.foldLineCount = viewCount;
        this.dayBetween = dayBetween;

        this.foldLinePoints = foldLineMaxPoints;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        foldLineDis = getRealWidth() / foldLineCount;
        drawVerticalAxis(canvas);
        drawCrossAxis(canvas);

        drawFoldLine(canvas);
        if (count == 1) {
            moveX = foldLineDis * (dayBetween-foldLineCount);
            firstMoveX = moveX;

            postInvalidate();
            count++;
        }

    }

    /**
     * 绘制横坐标轴
     *
     * @param canvas
     */
    private void drawCrossAxis(Canvas canvas) {
        canvas.save();
        Rect rectArea = new Rect(0, getPaddingTop(), getMeasuredWidth() - getPaddingRight(),
                getMeasuredHeight());
        canvas.clipRect(rectArea);
        Path axisPath = new Path();

//		Path axisScalePath = new Path();
        FontMetrics fontMetrics = crcossAxisTextPaint.getFontMetrics();
        int fontHeight = (int) (fontMetrics.descent - fontMetrics.ascent);// 字体的高度
        int startY = getAxisStartY();
        int startX = getAxisStartX();
        // 绘制横轴
        axisPath.setLastPoint(startX, startY);
        axisPath.lineTo(getMeasuredWidth() - getPaddingRight(), startY);

//		// 绘制横轴刻度
//		if (crossAxis != null) {// 若横轴有自定义刻度则绘制
//			for (int i = 0; i < crossAxis.size(); i++) {
//				XAxisScale axis = crossAxis.get(i);
//				int x = startX + (int) ((axis.getPercentPos() * 0.01f * getRealWidth() - axisWidth / 2));
//				axisScalePath.moveTo(x, startY);
//				axisScalePath.lineTo(x, startY + axisScaleWidth);// 绘制刻度
//				canvas.drawText(axis.getNum(), x - crcossAxisTextPaint.measureText(axis.getNum()) / 2,
//						startY + axisScaleWidth + fontHeight, crcossAxisTextPaint);// 绘制刻度单位
//			}
//		} else {// 若横轴无定义则根据折线点绘制
        int lastEndX = getCrossStartX() + moveX;// 首先计算出偏移，当已有的不能填充满屏幕时需要偏移到坐标起始位置
        System.out.println("crossSize" + crossAxis.size() + "," + foldLinePoints.size());
        for (int i = crossAxis.size() - 1; i >= 0; i--) {
            XAxisScale axis = crossAxis.get(i);
//				axisScalePath.moveTo(lastEndX, startY);
//				axisScalePath.lineTo(lastEndX, startY + axisScaleWidth);// 绘制刻度
            canvas.drawText("" + axis.getCount(),
                    lastEndX - crcossAxisTextPaint.measureText("" + axis.getCount()) / 2,
                    startY + axisScaleWidth + fontHeight, crcossAxisTextPaint);// 绘制刻度单位
            lastEndX -= foldLineDis;
        }
//		}
        if (foldLinePoints.size() == 0) {
            int x = (int) (getCrossStartX() + getRealWidth() - 5.5 * foldLineDis + (int) crossAxisPaint.measureText("暂无数据") / 2);

            canvas.drawText("暂无数据", x, getRealHeight() / 2 + getPaddingTop(), tipTextNODPaint);
        }
        canvas.drawPath(axisPath, crossAxisPaint);
//		canvas.drawPath(axisScalePath, crossAxispScalePaint);
        canvas.restore();
    }

    /**
     * 获取横轴的第一个点的开始坐标
     *
     * @return
     */
    private int getCrossStartX() {
        return getMeasuredWidth() - getPaddingRight()
                - (int) ( 0.5* foldLineDis);
    }

    int startMoveX;
    int endMoveX;

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        int currentTouchX = (int) event.getX();
//        int deltaX;
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                lastTouchX = (int) event.getX();
//
//                startMoveX = moveX;
//                getParent().requestDisallowInterceptTouchEvent(true);
//                break;
//            case MotionEvent.ACTION_MOVE:
//                deltaX = currentTouchX - lastTouchX;
//                if (Math.abs(deltaX) > 2) {
//
//                    moveX += deltaX;
//                    fillMoveValue();
//
//
//                    postInvalidate();
//                    lastTouchX = currentTouchX;
//                }
//                break;
//            case MotionEvent.ACTION_UP:
//                endMoveX = moveX;
//
//
//                moveX = startMoveX + Math.round((float) (endMoveX - startMoveX) / foldLineDis) * foldLineDis;
//                System.out.println("moveXxXx" + moveX);
//                if (listener != null) {
//                    listener.onMove(moveX);
//                }
//
//                lastTouchX = 0;
//                postInvalidate();
//                break;
//            default:
//                break;
//        }
//        return true;
//    }

    /**
     * 获取当向左边滑动时，左边坐标的最小值（防止坐标滑动超过坐标轴）
     *
     * @return
     */
    private int getLeftMoveMinCrossX() {
        return getAxisStartX() + foldLineDis;
    }

    /**
     * 获取当向右滑动时，右边坐标的最大值（防止坐标滑动超过坐标轴）
     *
     * @return
     */
    private int getRightMoveMaxCrossX() {
        return getFoldLineLength() - getAxisStartX();
    }

    /**
     * 对move的值进行修正，防止过度滑动
     *
     * @return
     */
    private void fillMoveValue() {
        int expectX = getCrossStartX() + moveX;
        if (expectX < getLeftMoveMinCrossX() + getMeasuredWidth() - foldLineDis * 7 - getPaddingRight()) {
            moveX = getLeftMoveMinCrossX() - getCrossStartX() + getMeasuredWidth() - getPaddingRight() - foldLineDis * 7;
        }

        int max = getRightMoveMaxCrossX();
        if (expectX > getRightMoveMaxCrossX() + foldLineDis * foldLineCount / 2) {
            moveX = getRightMoveMaxCrossX() - getCrossStartX() + foldLineDis * foldLineCount / 2;
        }
    }

    private int getFoldLineLength() {
        return foldLinePoints.size() * foldLineDis;
    }

    private void drawVerticalAxis(Canvas canvas) {
//        Path axisPath = new Path();
        Path axisScalePath = new Path();
        Path axisScaleAnPath = new Path();
        Path axisScaleDataPath = new Path();
        Path axisScaleTmpPath = new Path();
        FontMetrics fontMetrics = verticalAxisTextPaint.getFontMetrics();
        int fontHeight = (int) (fontMetrics.descent - fontMetrics.ascent);// 字体的高度
        FontMetrics anotherFontMetrics = verticalAxisLargePaint.getFontMetrics();
        int anotherFontHeight = (int) (anotherFontMetrics.descent - anotherFontMetrics.ascent);// 字体的高度
        int startY = getAxisStartY();
        int startX = getAxisStartX();
        // 绘制纵轴
        axisScalePath.setLastPoint(startX, startY);
        axisScalePath.lineTo(startX, startY - (int) (100 * 0.01f * getRealHeight() - axisWidth / 2));
        canvas.drawPath(axisScalePath, verticalAxisPaint);
        for (int i = 0; i < 11; i++) {

                int y = startY - (int) ((100 / 10.0 * i * 0.01f * getRealHeight()));
                axisScaleDataPath.moveTo(startX, y);
                axisScaleDataPath.lineTo(startX - axisScaleWidth, y);

                canvas.drawText("" + (min+i * (max-min)/10), startX - verticalAxisTextPaint.measureText("" + (min+i * (max-min)/10)) - axisScaleWidth - 5, y + fontHeight / 2,
                        verticalAxisTextPaint);

            canvas.drawPath(axisScaleDataPath, verticalAxisPaint);
        }
        for (int i = 0; i < 10; i++) {
            if (i != 0) {
                int y = startY - (int) ((100 / 9.0 * i * 0.01f * getRealHeight()));
                axisScaleTmpPath.moveTo(getMeasuredWidth() - getPaddingRight(), y);
                axisScaleTmpPath.lineTo(getMeasuredWidth() - getPaddingRight() + axisScaleWidth, y);
                canvas.drawPath(axisScaleTmpPath, verticalAxisPaint);

                canvas.drawText("" + i * 5, getMeasuredWidth() - getPaddingRight() + axisScaleWidth + 5, y + fontHeight / 2,
                        verticalAxisTextPaint);
            }
        }
        axisScaleAnPath.setLastPoint(getMeasuredWidth() - getPaddingRight(), startY);
        axisScaleAnPath.lineTo(getMeasuredWidth() - getPaddingRight(), startY - (int) (100 * 0.01f * getRealHeight() - axisWidth / 2));

        canvas.drawPath(axisScaleAnPath, crossAxispScalePaint);
        System.out.println("画纵坐标的两个x" + startX + ",," + getMeasuredWidth());
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void drawFoldLine(Canvas canvas) {
        canvas.save();
        if (foldLinePoints.size() != 0) {
            FontMetrics fontMetrics = crcossAxisTextPaint.getFontMetrics();
            int fontHeight = (int) (fontMetrics.descent - fontMetrics.ascent);
            Rect areaFold = new Rect(getAxisStartX(), 0
                    , getMeasuredWidth() - getPaddingRight(), getAxisStartY() + axisScaleWidth + fontHeight);// 折线图的绘制范围

            canvas.clipRect(areaFold);

//        Path foldPath = new Path();
            Path foldeLineDataPath = new Path();
            Path circleDataPath = new Path();
            Path foldeLineTmpPath = new Path();
            Path circleTmpPath = new Path();
            Path axisScalePath = new Path();


            int lastEndX = getCrossStartX() + moveX;// 首先计算出偏移，当已有的不能填充满屏幕时需要偏移到坐标起始位置

            int fisrtPointX = lastEndX;// 最左边的X坐标


            for (int i = foldLinePoints.size() - 1; i >= 0; i--) {
                JiSuLinePoint foldPonit = foldLinePoints.get(i);

                int dataY = getAxisStartY() - (int) (foldPonit
                        .getPercentY() * 0.01f * getRealHeight() - axisWidth / 2);
                int tmpY = getAxisStartY()  - (int) (foldPonit
                        .getPercentTmpY() * 0.01f * getRealHeight() - axisWidth / 2);
                if (i == foldLinePoints.size() - 1) {

                    circleDataPath.addCircle(lastEndX, dataY, DpXpExchange.dip2px(getContext(), 4), Direction.CCW);
                    foldeLineDataPath.moveTo(fisrtPointX, dataY);

                    circleTmpPath.addCircle(lastEndX, tmpY, DpXpExchange.dip2px(getContext(), 4), Direction.CCW);
                    foldeLineTmpPath.moveTo(fisrtPointX, tmpY);
                } else {
                    circleDataPath.addCircle(lastEndX, dataY, DpXpExchange.dip2px(getContext(), 4), Direction.CCW);
                    foldeLineDataPath.lineTo(lastEndX, dataY);

                    circleTmpPath.addCircle(lastEndX, tmpY, DpXpExchange.dip2px(getContext(), 4), Direction.CCW);
                    foldeLineTmpPath.lineTo(lastEndX, tmpY);
                }

                axisScalePath.moveTo(lastEndX, getPaddingTop());

                axisScalePath.lineTo(lastEndX, getAxisStartY() + 1);// 绘制刻度
//            foldPath.lineTo(lastEndX, y);


                // 绘制刻度单位
                lastEndX -= foldLineDis;
            }
            System.out.println("foldlineCount" + foldLineCount);

//
//        foldPath.lineTo(lastEndX + foldLineDis, getAxisStartY() - axisWidth * 2);
//        foldPath.lineTo(fisrtPointX, getAxisStartY() - axisWidth);
//        foldPath.lineTo(fisrtPointX, firstPointY);

            canvas.drawPath(axisScalePath, crossAxispScalePaint);
//        canvas.drawPath(foldPath, foldLineTmpPaint);
            canvas.drawPath(foldeLineDataPath, foldLineOutPaint);
            canvas.drawPath(foldeLineTmpPath, foldLineTmpPaint);
            canvas.drawPath(circleDataPath, foldLineCirclePaint);
            canvas.drawPath(circleTmpPath, foldLineCircleTmpPaint);


//            if (crossAxis.size() != 0) {
//                canvas.drawRoundRect(foldLineCount * foldLineDis / 2 + getAxisStartX() - DpXpExchange.dip2px(getContext(), 80), -10, foldLineCount * foldLineDis / 2 + getAxisStartX() + DpXpExchange.dip2px(getContext(), 80), DpXpExchange.dip2px(context,50)
//                        , 10, 10, rectFillPaint);
//            }


        }
        canvas.restore();
    }


    /**
     * 轴的起始X坐标
     *
     * @return
     */
    private int getAxisStartX() {

        FontMetrics fontMetris = verticalAxisTextPaint.getFontMetrics();


        return getPaddingLeft();


    }

    /**
     * 轴的起始Y坐标
     *
     * @return
     */
    private int getAxisStartY() {
        FontMetrics fontMetrics = crcossAxisTextPaint.getFontMetrics();
        int fontHeight = (int) (fontMetrics.descent - fontMetrics.ascent);// 字体的高度
        return getMeasuredHeight() - getPaddingBottom() - axisWidth / 2 - axisScaleWidth - fontHeight;
    }


    /**
     * 绘制内容区域的宽度
     *
     * @return
     */
    private int getRealWidth() {
        return getMeasuredWidth() - getAxisStartX() - getPaddingRight();
    }

    /**
     * 绘制内容区域的高度
     *
     * @return
     */
    private int getRealHeight() {
        return getAxisStartY() - getPaddingTop();
    }

    private int getRealLineHeight() {
        return (int) (getRealHeight() * 0.75);
    }

    public void setXaxisScale(List<XAxisScale> crossAxis, List<JiSuLinePoint> foldLinePoints
                              ,int min,int max
    ) {
        this.crossAxis = crossAxis;
        this.foldLinePoints = foldLinePoints;
        this.min = min;
        this.max = max;
//        moveX = foldLineDis * (dayBetween-foldLineCount) ;
//        firstMoveX = moveX;

        postInvalidate();
    }


    public int getFirstMoveX() {
        return firstMoveX;
    }

    public int getMoveX() {
        return moveX;
    }

    public void setMoveX(int dif) {
        moveX = moveX + dif * foldLineDis;
        postInvalidate();
    }


    public void setOnMoveListener(OnTmpViewMoveListener listener) {
        this.listener = listener;
    }


}
